Mode | Meaning of Mode | During Inexistence of file |
---|---|---|
r/rb | Open text/binary for reading. | If the file does not exist, open() returns None. |
w/wb | Open text/binary for writing. | If the file exists, its contents are overwritten. If the file does not exist, it will be created. |
a/ab | Open text/binary for append. i.e, Data is added to end of file. | If the file does not exists, it will be created. |
r+/rb+ | Open text/binary for both reading and writing. | If the file does not exist, open() returns None. |
w+/wb+ | Open text/binary for both reading and writing. | If the file exists, its contents are overwritten. If the file does not exist, it will be created. |
Method: | |
---|---|
read([size]) |
|
readline( ) |
|
readlines( ) | Return a list containing the lines. |
write(data) | Writes a data to the file. |
writelines(collection) | Writes a sequence of strings to the file. |
seek(offset[, whence]) |
|
tell( ) | Returns the file's current position. |
truncate([size]) | Truncates the file's size. If size is specified, the file is truncated to (at most) that size. |
close( ) | Close the file. |
file=open("c:/temp/info.txt") data=file.read() print(data) file.close()
P.Choudhari CCIT Rajapeth Amravati 444601
file=open("c:/temp/info.txt") data=file.read(4) print(data) data=file.read(6) print(data) file.close()
P.Ch oudhar
file=open("c:/temp/info.txt") data=file.readline() print(data) file.close()
P.Choudhari
file=open("c:/temp/info.txt") lst=file.readlines() i=1 for data in lst: print(i,":",data) i=i+1 file.close()
1: P.Choudhari 2: CCIT 3: Rajapeth Amravati 4: 444601
file=open("c:/temp/list.txt","w") data="Amit Jain\nRaja Rathi\nMona Mnatri" file.write(data) file.close() print("data stored. . .")
data stored...
data=input("Enter Name :") file=open("c:/temp/list.txt","a") file.write("\n"+data) file.close() print("data stored...")
Enter Name: Radha Rai data stored...
filex=open("c:\\temp\\hanuman.jpg","rb") data=filex.read() filex.close() filey=open("c:\\temp\\backup.jpg","wb") filey.write(data) filey.close() print("file copied")
File copied